﻿using System;
using System.Data;
using System.Data.Common;
using System.Transactions;

namespace Songhay.Data.GenericWeb.Procedures
{
    using Songhay.Data.GenericWeb.DataTransferContracts;
    using Songhay.Data.GenericWeb.Properties;

    /// <summary>
    /// Delete procedures into the DBMS.
    /// </summary>
    public static partial class Delete
    {
        /// <summary>
        /// Deletes the specified Segment.
        /// </summary>
        /// <param name="commonConnection">The Common connection.</param>
        /// <param name="segment">The Segment.</param>
        /// <returns>Returns the unique identifier of the deleted item.</returns>
        public static int? Segment(DbConnection commonConnection, ISegment segment)
        {
            if(commonConnection == null) throw new ArgumentNullException("commonConnection", "The Common Connection is null.");
            if(segment == null) throw new ArgumentNullException("segment", "The Input Segment is null.");

            int? id = segment.SegmentId;

            using(TransactionScope tscope = new TransactionScope())
            {
                using(DbCommand cmd = commonConnection.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = Resources.DeleteSegment;

                    DbParameter parameter;

                    parameter = cmd.CreateParameter();
                    parameter.ParameterName = "@SegmentId";
                    parameter.Value = id;
                    cmd.Parameters.Add(parameter);

                    cmd.ExecuteNonQuery();
                }

                using(DbCommand cmd = commonConnection.CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = Resources.DeleteSegmentDocument;

                    DbParameter parameter;

                    parameter = cmd.CreateParameter();
                    parameter.ParameterName = "@DocumentId";
                    parameter.Value = FrameworkType.SqlDatabaseNull();
                    cmd.Parameters.Add(parameter);

                    parameter = cmd.CreateParameter();
                    parameter.ParameterName = "@SegmentId";
                    parameter.Value = id;
                    cmd.Parameters.Add(parameter);

                    cmd.ExecuteNonQuery();
                }

                tscope.Complete();

            }

            return id;
        }
    }
}
